package cn.cuilan.secondkill.controller;

import cn.cuilan.secondkill.service.SecondKillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.concurrent.CountDownLatch;

@Controller
public class TestController {

    private int threadCount = 1000;

    private Thread[] threads = new Thread[threadCount];

    private CountDownLatch beginCount = new CountDownLatch(1);

    private CountDownLatch endCount = new CountDownLatch(threadCount);

    private SecondKillService secondKillService;

    @Autowired
    public TestController(SecondKillService secondKillService) {
        this.secondKillService = secondKillService;
    }

    @GetMapping("/begin")
    public String begin() {

        for (int i = 0; i < threadCount; i++) {
            threads[i] = new Thread(() -> {
                try {
                    beginCount.await();
                    Thread thread = Thread.currentThread();
                    while (true){
                        String result = secondKillService.push("userId:" + thread.getId());
                        System.out.println("Thread: " + thread.getId() + ", " + result);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, "Thread:" + i);
            threads[i].start();
        }

        beginCount.countDown();

        return "OK";
    }

}
